﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Data;
using System.Text;
using System.Web;
using System.Transactions;
using FreedomERP.Services.Bd.Impl;
using FreedomERP.Models;
using FreedomERP.Comm;
using FreedomERP.Comm.Utils;
using FreedomERP.Comm.DB;

namespace FreedomERP.Dao.Bd.Impl
{
    /// <summary>
    /// 商家信息管理数据库实现
    /// 作者：陈新杰
    /// </summary>
    public class BdOrgunitDaoImpl : IBdOrgunitDao
    {


        FreedomERPEntities dbEntities = new FreedomERPEntities();


        public DAOResult<String> findOrgunitId(String fOrgunitName)
        {
            if (fOrgunitName == null)
            {
                return new DAOResult<String>(false, "商家名字为空，无法查询", null);
            }
            else
            {
                BdOrgunit bdOrgunit = (from orgunit in dbEntities.BdOrgunit where orgunit.FName == fOrgunitName select orgunit).First<BdOrgunit>();
                if (bdOrgunit != null)
                {
                    List<String> resultSet = new List<String>();
                    resultSet.Add(bdOrgunit.FId);
                    return new DAOResult<String>(true, null, resultSet);
                }
                else
                {
                    return new DAOResult<String>(false, "该商家不存在", null);

                }
            }
        }

        public DAOResult<BdOrgunit> findOrgunit(String fId, String fOrgunitName, String fOrgunitNumber, int start, int limit)
        {
            Expression<Func<BdOrgunit, bool>> predicate = PredicateExtensions.True<BdOrgunit>();
            if (fId != null)
            {
                predicate = predicate.And(orgUnit => orgUnit.FId.Contains(fId));
            }
            if (fOrgunitName != null)
            {
                predicate = predicate.And(orgUnit => orgUnit.FName.Contains(fOrgunitName));
            }
            if (fOrgunitNumber != null)
            {
                predicate = predicate.And(orgUnit => orgUnit.FNumber.Contains(fOrgunitNumber));
            }
            List<BdOrgunit> orgUnits = dbEntities.BdOrgunit.Where(predicate).OrderBy(orgUnit => orgUnit.FNumber).Skip(start).Take(limit).ToList();
            return new DAOResult<BdOrgunit>(true, null, orgUnits);

        }


        /// <summary>
        /// 根据商家ID获取商家信息
        /// </summary>
        /// <param name="fId"></param>
        /// <returns></returns>
        public BdOrgunit findOrgunitById(String fId)
        {
            BdOrgunit bdOrgunit = null;
            List<BdOrgunit> orgList = (from org in dbEntities.BdOrgunit where org.FId.Equals(fId) select org).ToList<BdOrgunit>();
            if (orgList != null && orgList.Count > 0)
            {
                bdOrgunit = orgList.First();
            }
            return bdOrgunit;
        }


    }
}